package Thread.ConsumerAndProducer.method1;

import java.util.concurrent.locks.Lock;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}10:03
 */
public class Test {
    private static Integer count = 0;
    private static final Integer FULL = 10;
    private static String LOCK = "lock";


    Thread producer = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0 ; i < 10; i++){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (LOCK){
                    while (count == FULL){//生产者满了
                        try {
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName()+"生成者生产，目前总共有"+count);
                    LOCK.notifyAll();//为消费者那边发出通知
                }
            }
        }
    });

    Thread consumer = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (LOCK){
                    while (count==0){
                        try {
                            LOCK.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName()+"消费者消费，目前总共有"+count);
                    LOCK.notifyAll();//通知正在等待的生产者（生成满的情况下）可以开始生产了
                }
            }
        }
    });

    public static void main(String[] args) {
        new Test().producer.start();
        new Test().consumer.start();
        new Test().producer.start();
    }
}
